﻿using System.Diagnostics;

namespace SimpleX.Tracing
{
    public class TraceIdManager : ITraceIdManager
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public TraceIdManager(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public string GetTraceId()
        {
            var httpContext = _httpContextAccessor.HttpContext;
            if (httpContext == null)
                return string.Empty;

            if (httpContext.Items.TryGetValue("__TraceId_HAND_LOONG", out var traceId))
                return traceId as string;

            return string.Empty;
        }

        public void SetTraceId(string traceId)
        {
            var httpContext = _httpContextAccessor.HttpContext;
            if (httpContext != null)
                httpContext.Items["__TraceId_HAND_LOONG"] = traceId;
        }

        public string GenerateNewTraceId()
        {
            return Guid.NewGuid().ToString("N");
        }
    }
}
